using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using C4F.DevKit.Bluetooth.FileTransferProfile;
using C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery;
using System.Net.Sockets;
using System.IO;
using Microsoft.VisualBasic;
using System.Xml;

namespace FileTransferProfileApplication
{
    public partial class Form1 : Form
    {

        #region Private Fields       
        
        List<Device> devList = null;
        RemoteService FTPService = null;
        NetworkStream networkStream = null;
        List<RemoteService> FTPServiceList;
        TreeNode selectedNode;
        bool isAsync = true;
        #endregion

        #region Constructor
        /// <summary>
        /// Initializes the form
        /// </summary>
        public Form1()
        {
            InitializeComponent();

        }

        #endregion

        #region EventHandlers
        // Event Handler for btnDiscover. Performs Device Discovery.
        private void btnDiscover_Click(object sender, EventArgs e)
        {
            try
            {
                cmbDevice.Items.Clear();
                cmbServices.Items.Clear();
                cmbDevice.Text = "";
                cmbServices.Text = "";
                cmbServices.Enabled = false;
                btnConnect.Enabled = false;
                btnOperation.Enabled = false;
                tvFolderHierarchy.Nodes.Clear();
                txtCurrentDirectory.Text = "";
                btnRefreshFold.Enabled = false;

                this.Cursor = Cursors.WaitCursor;
                devList = deviceServicesManager1.DiscoverAllDevices();
                if (devList.Count != 0)
                {
                    foreach (Device dev in devList)
                        cmbDevice.Items.Add(dev.Name);
                }
                if (devList.Count > 0)
                {
                    cmbServices.Enabled = true;

                }
            }
            catch (Exception ex)
            {
                string errorMsg = ex.Message;
                if (ex.InnerException != null)
                    errorMsg += Environment.NewLine + ex.InnerException.Message;

                MessageBox.Show("Unable to discover devices. " + errorMsg,
                                "FileTransferProfile Application", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        // Event Handler for cmbServices.Performs service discovery on 
        //selected device. Searches only for File Transfer Service.
        private void cmbServices_Enter(object sender, EventArgs e)
        {
            try
            {
                cmbServices.Items.Clear();
                if (devList != null && devList.Count != 0)
                {
                    foreach (Device dev in devList)
                    {
                        if (dev.Name == cmbDevice.Text)
                        {
                            FTPServiceList =
                                deviceServicesManager1.DiscoverServicesByType(dev, ServiceType.OBEXFileTransfer);
                            if (FTPServiceList != null && FTPServiceList.Count != 0)
                            {
                                foreach (RemoteService remServ in FTPServiceList)
                                {
                                    cmbServices.Items.Add(remServ.Name);
                                }
                            }
                            break;
                        }
                    }
                }
                if (cmbServices.Items.Count > 0)
                    btnConnect.Enabled = true;
            }
            catch (Exception ex)
            {
                btnConnect.Enabled = false;
                cmbServices.Enabled = true;
                tvFolderHierarchy.Enabled = false;

                string errorMsg = ex.Message;
                if (ex.InnerException != null)
                    errorMsg += ex.InnerException.Message;

                MessageBox.Show("Unable to discover services on remote device. " + errorMsg,
                                "FileTransferProfile Application", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
        }
        // Event Handler for btnConnect.Connects to the remote device.
        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                if (string.IsNullOrEmpty(cmbServices.Text))
                {
                    MessageBox.Show("Please select a service for performing File Transfer operations.",
                                    "FileTransferProfile Application",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    cmbServices.Focus();
                }
                else
                {
                    foreach (RemoteService rem in FTPServiceList)
                    {

                        if (cmbServices.Text == rem.Name)
                        {
                            FTPService = rem;
                            networkStream = FTPService.Connect();

                            btnConnect.Enabled = false;
                            cmbServices.Enabled = false;
                            tvFolderHierarchy.Enabled = true;
                            btnOperation.Enabled = true;
                            btnRefreshFold.Enabled = true;

                            ftpManager1.NetworkStream = networkStream;
                            

                            //Initializes the event handlers
                            ftpManager1.CreateFolderCompleted +=
                                new BluetoothFTPManager.CreateFolderCompletedEventHandler(ftpManager1_CreateFolderCompleted);
                            ftpManager1.DeleteFileCompleted +=
                                new BluetoothFTPManager.DeleteFileCompletedEventHandler(ftpManager1_DeleteFileCompleted);
                            ftpManager1.DeleteFolderCompleted +=
                                new BluetoothFTPManager.DeleteFolderCompletedEventHandler(ftpManager1_DeleteFolderCompleted);
                            ftpManager1.GetFileCompleted +=
                                new BluetoothFTPManager.GetFileCompletedEventHandler(ftpManager1_GetFileCompleted);
                            ftpManager1.GetFolderCompleted +=
                                new BluetoothFTPManager.GetFolderCompletedEventHandler(ftpManager1_GetFolderCompleted);

                            ftpManager1.SendFileCompleted +=
                                new BluetoothFTPManager.SendFileCompletedEventHandler(ftpManager1_SendFileCompleted);
                            ftpManager1.SendFolderCompleted +=
                                new BluetoothFTPManager.SendFolderCompletedEventHandler(ftpManager1_SendFolderCompleted);
                            ftpManager1.SetCurrentDirectoryCompleted +=
                                new BluetoothFTPManager.SetCurrentDirectoryCompletedEventHandler(ftpManager1_SetCurrentDirectoryCompleted);
                            ftpManager1.Connect();

                            // Get the folder listing of the remote device.
                            TreeNode node = new TreeNode("\\");
                            node.Tag = "folder";
                            tvFolderHierarchy.Nodes.Add(node);
                            break;
                        }
                    }

                }
            }
            catch (ServiceConnectionException servEx)
            {
                btnConnect.Enabled = true;
                cmbServices.Enabled = true;
                tvFolderHierarchy.Enabled = false;

                string errorMsg = servEx.Message;
                if (servEx.InnerException != null)
                    errorMsg += servEx.InnerException.Message;

                MessageBox.Show(errorMsg, "FileTransferProfile Application",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (FTPException ftpEx)
            {
                btnConnect.Enabled = true;
                cmbServices.Enabled = true;
                tvFolderHierarchy.Enabled = false;

                string errorMsg = ftpEx.Message;
                if (ftpEx.InnerException != null)
                    errorMsg += ftpEx.InnerException.Message;

                MessageBox.Show(errorMsg, "FileTransferProfile Application",
                               MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                btnConnect.Enabled = true;
                cmbServices.Enabled = true;
                tvFolderHierarchy.Enabled = false;

                string errorMsg = ex.Message;
                if (ex.InnerException != null)
                    errorMsg += ex.InnerException.Message;

                MessageBox.Show(errorMsg, "FileTransferProfile Application",
                               MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        // Event Handler for SetCurrentDirectoryCompleted event.
        private void ftpManager1_SetCurrentDirectoryCompleted(object sender, SetCurrentDirectoryCompletedEventArgs e)
        {
            if (isAsync)
            {
            }
            else isAsync = true;
        }
        // Event Handler for SendFolderCompleted event.
        private void ftpManager1_SendFolderCompleted(object sender, SendFolderCompletedEventArgs e)
        {
            if (isAsync)
            {
                if (e.Error == null)
                {
                    MessageBox.Show("Asynchronous Send Folder Operation Completed. " + Environment.NewLine
                                    + "Folder Name:" + e.LocalFolderPath, "FileTransferProfile Application",
                                     MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ftpManager1.SetCurrentDirectory(txtCurrentDirectory.Text);
                }
                else
                {
                    string errorMsg = e.Error.Message;
                    if (e.Error.InnerException != null)
                        errorMsg += Environment.NewLine + e.Error.InnerException.Message;

                    MessageBox.Show(errorMsg, "FileTransferProfile Application",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
            else
            {
                if(e.Error == null)
                    ftpManager1.SetCurrentDirectory(txtCurrentDirectory.Text);

                isAsync = true;
            }
            
        }
        // Event Handler for SendFileCompleted event.
        private void ftpManager1_SendFileCompleted(object sender, SendFileCompletedEventArgs e)
        {
            if (isAsync)
            {
                if (e.Error == null)
                {
                    MessageBox.Show("Asynchronous Send File Operation Completed. " + Environment.NewLine
                                    + "File Name:" + e.LocalFilePath, "FileTransferProfile Application",
                                     MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    string errorMsg = e.Error.Message;
                    if (e.Error.InnerException != null)
                        errorMsg += Environment.NewLine + e.Error.InnerException.Message;

                    MessageBox.Show(errorMsg, "FileTransferProfile Application",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
            else isAsync = true;
        }
        // Event Handler for GetFolderCompleted event.
        private void ftpManager1_GetFolderCompleted(object sender, GetFolderCompletedEventArgs e)
        {

            if (isAsync)
            {
                if (e.Error == null)
                {
                    MessageBox.Show("Asynchronous Get Folder Operation Completed. "
                                    + Environment.NewLine + "Folder Name:" + e.RemoteFolderPath,
                                    "FileTransferProfile Application",
                                     MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    string errorMsg = "An Asynchronous Get Folder Operation has failed. Error details: " +  e.Error.Message;
                    if (e.Error.InnerException != null)
                        errorMsg += Environment.NewLine + e.Error.InnerException.Message;
                    MessageBox.Show(errorMsg, "FileTransferProfile Application",
                                     MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else isAsync = true;
           // txtCurrentDirectory.Text = e.RemoteFolderPath;
        }
        // Event Handler for GetFileCompleted event.
        private void ftpManager1_GetFileCompleted(object sender, GetFileCompletedEventArgs e)
        {
            if (isAsync)
            {
                if (e.Error == null)
                {
                    try
                    {
                        if (!string.IsNullOrEmpty(folderBrowserDialog1.SelectedPath))
                        {
                            File.WriteAllBytes(folderBrowserDialog1.SelectedPath + "\\"
                                                + e.RemoteFilePath.Substring(e.RemoteFilePath.LastIndexOf('\\') + 1),
                                                e.FileContent);

                            MessageBox.Show("Asynchronous Get File Operation Completed. " + Environment.NewLine
                                            + "File Name:" + e.RemoteFilePath, "FileTransferProfile Application",
                                               MessageBoxButtons.OK, MessageBoxIcon.Information);

                            //string dir = e.RemoteFilePath;
                            //dir = dir.Substring(0, dir.LastIndexOf("\\"));
                            //txtCurrentDirectory.Text = e.RemoteFolderPath;
                        }
                    }
                    catch (Exception ex)
                    {
                        string errorMsg = "An Asynchronous Get File Operation has failed. Error details: " + ex.Message;
                        if (ex.InnerException != null)
                            errorMsg += Environment.NewLine + ex.InnerException.Message;
                        MessageBox.Show(errorMsg,
                                   "FileTransferProfile Application",
                                   MessageBoxButtons.OK, MessageBoxIcon.Error);
                        
                        //txtCurrentDirectory.Text = e.RemoteFolderPath;
                    }

                }
                else
                {

                    string errorMsg = "An Asynchronous Get File Operation has failed. Error details: " + e.Error.Message;
                    if (e.Error.InnerException != null)
                        errorMsg += Environment.NewLine + e.Error.InnerException.Message;

                    MessageBox.Show(errorMsg,
                                    "FileTransferProfile Application",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else isAsync = true;
            
        }
        // Event Handler for DeleteFolderCompleted event.
        private void ftpManager1_DeleteFolderCompleted(object sender, DeleteFolderCompletedEventArgs e)
        {
            if (isAsync)
            {
                if (e.Error == null)
                {
                    MessageBox.Show("Asynchronous Delete Folder Operation Completed. "
                                    + Environment.NewLine + "Folder Name:" + e.RemoteFolderPath,
                                    "FileTransferProfile Application",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    string dir = e.RemoteFolderPath;                    
                    dir = dir.Substring(0, dir.LastIndexOf("\\"));
                    txtCurrentDirectory.Text = dir;
                }
                else
                {
                    string errorMsg = "An Asynchronous Delete Folder Operation has failed. Error details: "
                                        + e.Error.Message;
                    if (e.Error.InnerException != null)
                        errorMsg += Environment.NewLine + e.Error.InnerException.Message;

                    MessageBox.Show(errorMsg,
                                    "FileTransferProfile Application",
                                     MessageBoxButtons.OK, MessageBoxIcon.Error);

                    txtCurrentDirectory.Text = e.RemoteFolderPath;
                }
            }
            else
            {
                if (e.Error == null)
                {
                    string dir = e.RemoteFolderPath;
                    dir = dir.Substring(0, dir.LastIndexOf("\\"));
                    txtCurrentDirectory.Text = e.RemoteFolderPath;
                }
                else
                    txtCurrentDirectory.Text = e.RemoteFolderPath;
                isAsync = true;
            }
            
           
        }
        // Event Handler for DeleteFileCompleted event.
        private void ftpManager1_DeleteFileCompleted(object sender, DeleteFileCompletedEventArgs e)
        {
            if (isAsync)
            {
                if (e.Error == null)
                {
                    MessageBox.Show("Asynchronous Delete File Operation Completed. "
                                    + Environment.NewLine + "File Name:" + e.RemoteFilePath,
                                    "FileTransferProfile Application",
                                     MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                   string errorMsg = "An Asynchronous Delete File Operation has failed. Error details: "  
                                        + e.Error.Message;
                    if (e.Error.InnerException != null)
                        errorMsg += Environment.NewLine + e.Error.InnerException.Message;

                    MessageBox.Show(errorMsg, "FileTransferProfile Application",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else isAsync = true;
        }
        // Event Handler for CreateFolderCompleted event.
        private void ftpManager1_CreateFolderCompleted(object sender, CreateFolderCompletedEventArgs e)
        {
            if (isAsync)
            {
                if (e.Error == null)
                {
                    MessageBox.Show("Asynchronous Create Folder Operation Completed. "
                                    + Environment.NewLine + "Folder Name:" + e.RemoteFolderPath,
                                    "FileTransferProfile Application",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);

                    ftpManager1.SetCurrentDirectory(txtCurrentDirectory.Text);
                }
                else
                {
                    string errorMsg = "An Asynchronous Create Folder Operation has failed. Error details: "
                                    + e.Error.Message;
                    if (e.Error.InnerException != null)
                        errorMsg += Environment.NewLine + e.Error.InnerException.Message;
                    MessageBox.Show(errorMsg,
                                    "FileTransferProfile Application",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {   
                if(e.Error == null)
                    ftpManager1.SetCurrentDirectory(txtCurrentDirectory.Text);
                isAsync = true;
            }
        }
        // Event Handler for Form Load event.
        private void Form1_Load(object sender, EventArgs e)
        {

            cmbDevice.Items.Clear();
            cmbServices.Items.Clear();
            cmbDevice.Text = "";
            cmbServices.Text = "";
            cmbServices.Enabled = false;
            btnConnect.Enabled = false;
            btnOperation.Enabled = false;
            tvFolderHierarchy.Nodes.Clear();
            txtCurrentDirectory.Text = "";
            btnRefreshFold.Enabled = false;

            try
            {
                devList = deviceServicesManager1.DiscoverAllDevices();
                if (devList.Count != 0)
                {
                    foreach (Device dev in devList)
                        cmbDevice.Items.Add(dev.Name);
                }
                if (devList.Count > 0)
                {
                    cmbServices.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                string errorMsg = ex.Message;

                if (ex.InnerException != null)
                    errorMsg += Environment.NewLine + ex.InnerException.Message;

                MessageBox.Show("Unable to discover devices." + errorMsg,
                               "FileTransferProfile Application", MessageBoxButtons.OK,
                               MessageBoxIcon.Error);
            }

        }
        // Event Handler for Tree view NodeMouseClick event.
        private void tvFolderHierarchy_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {

            if (e.Button == MouseButtons.Right)
            {
                selectedNode = e.Node;

                contextMenuStrip1.Items.Clear();

                contextMenuStrip1.Items.Add("Pull Sync");
                contextMenuStrip1.Items.Add("Pull Async");
                contextMenuStrip1.Items.Add("Delete Sync");
                contextMenuStrip1.Items.Add("Delete Async");

                if (e.Node.Tag.ToString() == "folder")
                {
                    // Add create folder options
                    contextMenuStrip1.Items.Add("Create SubFolder Sync");
                    contextMenuStrip1.Items.Add("Create SubFolder Async");

                }
                contextMenuStrip1.Show();
                selectedNode.ContextMenuStrip = contextMenuStrip1;
            }
            else
            {
                selectedNode = e.Node;
                this.Cursor = Cursors.WaitCursor;
                if (e.Node.Tag.ToString() == "folder")
                {
                    if (e.Node.GetNodeCount(false) > 0)
                        e.Node.Nodes.Clear();
                    GetFolderListing(e.Node.FullPath);
                }
                this.Cursor = Cursors.Default;
            }
        }
        // Event Handler for contextMenuStrip1 ItemClicked event.
        private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            string selectedCommand = e.ClickedItem.Text;
            selectedNode.ContextMenuStrip = null;
            contextMenuStrip1.Hide();
            this.Cursor = Cursors.WaitCursor;

            try
            {
                switch (selectedCommand)
                {
                    case "Pull Sync":
                        isAsync = false;
                        if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                        {
                            isAsync = false;
                            if (selectedNode.Tag.ToString() == "folder")
                            {
                                try
                                {
                                    if (!string.IsNullOrEmpty(selectedNode.FullPath) &&
                                   !string.IsNullOrEmpty(folderBrowserDialog1.SelectedPath))
                                    {
                                        ftpManager1.GetFolder(selectedNode.FullPath,
                                                             folderBrowserDialog1.SelectedPath);

                                        MessageBox.Show("Synchronous Get Folder Operation Completed. " +
                                                        Environment.NewLine + "Received Folder: " + selectedNode.FullPath,
                                                        "FileTransferProfile Application",
                                                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    string errorMsg = "A Synchronous Get Folder Operation has failed. Error details: " + ex.Message;
                                    if (ex.InnerException != null)
                                        errorMsg += ex.InnerException.Message;

                                    MessageBox.Show(errorMsg,
                                                    "FileTransferProfile Application",
                                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }

                            }
                            else
                            {
                                try
                                {
                                    if (!string.IsNullOrEmpty(selectedNode.FullPath) &&
                                    !string.IsNullOrEmpty(folderBrowserDialog1.SelectedPath))
                                    {
                                        File.WriteAllBytes(folderBrowserDialog1.SelectedPath + "\\" + selectedNode.Text,
                                        ftpManager1.GetFile(selectedNode.FullPath));

                                        MessageBox.Show("Synchronous Get File Operation Completed. " +
                                                        Environment.NewLine + "Received File: " + selectedNode.FullPath,
                                                        "FileTransferProfile Application",
                                                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    string errorMsg = "A Synchronous Get File Operation has failed. Error details: " + ex.Message;
                                    if (ex.InnerException != null)
                                        errorMsg += ex.InnerException.Message;

                                    MessageBox.Show(errorMsg, "FileTransferProfile Application",

                                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                        }


                        break;

                    case "Pull Async":

                        if (selectedNode.Tag.ToString() == "folder")
                        {
                            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                                if (!string.IsNullOrEmpty(selectedNode.FullPath) &&
                                    !string.IsNullOrEmpty(folderBrowserDialog1.SelectedPath))
                                {
                                    ftpManager1.GetFolderAsync(selectedNode.FullPath,
                                                              folderBrowserDialog1.SelectedPath, null);
                                }
                        }
                        else
                        {
                            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                            {
                                if (!string.IsNullOrEmpty(selectedNode.FullPath) &&
                                   !string.IsNullOrEmpty(folderBrowserDialog1.SelectedPath))
                                {
                                    ftpManager1.GetFileAsync(selectedNode.FullPath, null);
                                }
                            }
                        }



                        break;

                    case "Delete Sync":
                        isAsync = false;

                        if (selectedNode.Tag.ToString() == "folder")
                        {
                            try
                            {
                                if (!string.IsNullOrEmpty(selectedNode.FullPath))
                                {
                                    ftpManager1.DeleteFolder(selectedNode.FullPath, true);
                                    MessageBox.Show("Synchronous Delete Folder Operation Completed. " +
                                                    Environment.NewLine + "Deleted Folder: " + selectedNode.FullPath,
                                                    "FileTransferProfile Application",
                                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                                
                            }
                            catch (Exception ex)
                            {
                                string errorMsg = "A Synchronous Delete Folder Operation has failed. Error details: " + ex.Message;
                                if (ex.InnerException != null)
                                    errorMsg += ex.InnerException.Message;
                                MessageBox.Show(errorMsg,
                                                "FileTransferProfile Application",
                                                MessageBoxButtons.OK, MessageBoxIcon.Error);

                            }

                        }


                        else
                        {
                            try
                            {
                                if (!string.IsNullOrEmpty(selectedNode.FullPath))
                                {
                                    ftpManager1.DeleteFile(selectedNode.FullPath);
                                    MessageBox.Show("Synchronous Delete File Operation Completed. " +
                                                    Environment.NewLine + "Deleted File: " + selectedNode.FullPath,
                                                    "FileTransferProfile Application",
                                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                            }
                            catch (Exception ex)
                            {
                                string errorMsg = "A Synchronous Delete File Operation has failed. Error details: " + ex.Message;
                                if (ex.InnerException != null)
                                    errorMsg += ex.InnerException.Message;
                                MessageBox.Show(errorMsg,
                                                "FileTransferProfile Application",
                                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }


                        break;


                    case "Delete Async":
                        if (selectedNode.Tag.ToString() == "folder")
                        {
                            if (!string.IsNullOrEmpty(selectedNode.FullPath))
                                ftpManager1.DeleteFolderAsync(selectedNode.FullPath, true, null);
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(selectedNode.FullPath))
                                ftpManager1.DeleteFileAsync(selectedNode.FullPath, null);
                        }
                        break;

                    case "Create SubFolder Sync":
                        try
                        {
                            isAsync = false;
                            if (selectedNode.Tag.ToString() == "folder")
                            {
                                string folderName = "";
                                do
                                {
                                    folderName = Interaction.InputBox("Enter a folder name. ", "Create Folder",
                                           "Folder1", 200, 200);
                                    if (folderName == "Folder1" || folderName == string.Empty)
                                        break;
                                }
                                while (string.IsNullOrEmpty(folderName.Trim()));
                                if (!string.IsNullOrEmpty(folderName.Trim()))
                                {
                                    if (!string.IsNullOrEmpty(selectedNode.FullPath))
                                    {
                                        ftpManager1.CreateFolder(selectedNode.FullPath + "\\" + folderName, true);
                                        MessageBox.Show("Synchronous Create Folder Operation Completed. " +
                                                        Environment.NewLine + "Created Folder: " + folderName +
                                                        " At location " + selectedNode.FullPath + " on remote device.",
                                                        "FileTransferProfile Application",
                                                        MessageBoxButtons.OK, MessageBoxIcon.Information);

                                       

                                    }
                                }
                            }

                        }
                        catch (Exception ex)
                        {
                            string errorMsg = "A Synchronous Create Folder Operation has failed. Error details: " + ex.Message;
                            if (ex.InnerException != null)
                                errorMsg += ex.InnerException.Message;
                            MessageBox.Show(errorMsg,
                                            "FileTransferProfile Application",
                                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                            
                        }
                        break;

                    case "Create SubFolder Async":
                        if (selectedNode.Tag.ToString() == "folder")
                        {
                            string folderName = "";
                            do
                            {
                                folderName = Interaction.InputBox("Enter a folder name. ", "Create Folder",
                                   "Folder1", 200, 200);
                                if (folderName == "Folder1" || folderName == string.Empty)     
                                    break;
                                                                
                            }
                            while (string.IsNullOrEmpty(folderName.Trim()));
                            if (!string.IsNullOrEmpty(folderName.Trim()))
                            {
                                if (!string.IsNullOrEmpty(selectedNode.FullPath))
                                    ftpManager1.CreateFolderAsync(selectedNode.FullPath + "\\" + folderName, true, null);
                            }

                        }
                        break;
                }
            }

            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        // Event Handler for btnOperation Click event.Performs the Push Operations.
        private void btnOperation_Click(object sender, EventArgs e)
        {
            switch (cmbPushOperations.Text)
            {
                case "Push File Sync":
                    try
                    {
                        isAsync = false;
                        if (openFileDialog1.ShowDialog() == DialogResult.OK)
                        {
                            if (!string.IsNullOrEmpty(openFileDialog1.FileName))
                            {
                                ftpManager1.SendFile(openFileDialog1.FileName);
                                MessageBox.Show("Synchronous Send File Operation Completed." +
                                                Environment.NewLine + "Pushed File: " + openFileDialog1.FileName,
                                                "FileTransferProfile Application",
                                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        string errorMsg = "A Synchronous Send File Operation has failed. Error details: " + ex.Message;
                        if (ex.InnerException != null)
                            errorMsg += ex.InnerException.Message;
                        MessageBox.Show(errorMsg,
                                        "FileTransferProfile Application",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "Push File Async":

                    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        if (!string.IsNullOrEmpty(openFileDialog1.FileName))
                        {
                            ftpManager1.SendFileAsync(openFileDialog1.FileName, null);
                        }
                    }


                    break;
                case "Push Folder Sync":
                    try
                    {
                        isAsync = false;
                        if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                        {
                            if (!string.IsNullOrEmpty(folderBrowserDialog1.SelectedPath))
                            {
                                ftpManager1.SendFolder(folderBrowserDialog1.SelectedPath);
                                MessageBox.Show("Synchronous Send Folder Operation Completed. " +
                                                Environment.NewLine + "Pushed Folder: " + folderBrowserDialog1.SelectedPath,
                                                "FileTransferProfile Application",
                                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        string errorMsg = "A Synchronous Send Folder Operation has failed. Error details: " + ex.Message;
                        if (ex.InnerException != null)
                            errorMsg += ex.InnerException.Message;
                        MessageBox.Show(errorMsg,
                                        "FileTransferProfile Application",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "Push Folder Async":
                    if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                    {
                        if (!string.IsNullOrEmpty(folderBrowserDialog1.SelectedPath))
                        {
                            ftpManager1.SendFolderAsync(folderBrowserDialog1.SelectedPath, null);
                        }
                    }
                    break;
            }

        }
        // Event Handler for btnExit Click event.Exits the application after disconnecting from the service.
        private void btnExit_Click(object sender, EventArgs e)
        {
            try
            {
                if(ftpManager1.NetworkStream != null)
                    ftpManager1.Disconnect();
                if(FTPService!=null)
                FTPService.Disconnect();
            }
            catch (Exception ex)
            {

                if (ex is FTPException || ex.InnerException is FTPException)
                    MessageBox.Show("An Error occured while disconnecting from File Transfer Service on " +
                                    "remote device. " + ex.Message, "FileTransferProfile Application",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);

                else

                    MessageBox.Show("An Error occured while disconnecting from remote device. "
                                    + ex.Message, "FileTransferProfile Application",
                                     MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Close();
            }
        }
        // Event Handler for btnRefreshFold Click event.Sets current directory to that of root.
        private void btnRefreshFold_Click(object sender, EventArgs e)
        {
            //Sets the current directory to that of root.
            try
            {
                this.Cursor = Cursors.WaitCursor;
                ftpManager1.SetCurrentDirectory("\\");
                tvFolderHierarchy.Nodes.Clear();
                TreeNode node = new TreeNode("\\");
                node.Tag = "folder";
                tvFolderHierarchy.Nodes.Add(node);
                txtCurrentDirectory.Text = "\\";
            }
            catch (Exception ex)
            {
                string errorMsg = ex.Message;
                if (ex.InnerException != null)
                    errorMsg += ex.InnerException.Message;

                MessageBox.Show("Error in Setting current directory to that of root directory. " + errorMsg,
                         "FileTransferProfile Application",
                         MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        #endregion

        #region Private Functions
        //Gets the folder listing of current directory.
        private void GetFolderListing(string Path)
        {
            try
            {
                XmlDocument folderlisting = ftpManager1.GetFolderListing(Path);
                txtCurrentDirectory.Text = Path;
                if (folderlisting != null)
                {
                    //Get a list of folders
                    XmlNodeList folderList = folderlisting.GetElementsByTagName("folder");
                    //Get a list of files
                    XmlNodeList fileList = folderlisting.GetElementsByTagName("file");
                    //For each file in the list get its contents and then create a file on local
                    //device with received file content.
                    if (fileList != null && fileList.Count != 0)
                    {
                        foreach (XmlNode node in fileList)
                        {
                            XmlAttributeCollection attrCollection = node.Attributes;
                            if (attrCollection != null && attrCollection.Count != 0)
                            {
                                XmlNode attrNode = attrCollection.GetNamedItem("name");
                                if (attrNode != null)
                                {
                                    TreeNode trvNode = new TreeNode(attrNode.Value);
                                    trvNode.Tag = "file";
                                    selectedNode.Nodes.Add(trvNode);
                                }
                            }

                        }
                    }
                    //For each folder in the list create a folder on local device.
                    if (folderList != null && folderList.Count != 0)
                    {
                        foreach (XmlNode node in folderList)
                        {
                            XmlAttributeCollection attrCollection = node.Attributes;
                            if (attrCollection != null && attrCollection.Count != 0)
                            {
                                XmlNode attrNode = attrCollection.GetNamedItem("name");
                                if (attrNode != null)
                                {
                                    TreeNode trvNode = new TreeNode(attrNode.Value);
                                    trvNode.Tag = "folder";
                                    bool isPresent = false;
                                    foreach (TreeNode trvChildNode in selectedNode.Nodes)
                                    {
                                        if (trvChildNode.Text == trvNode.Text)
                                        {
                                            isPresent = true;
                                            break;
                                        }
                                    }
                                    if (!isPresent)
                                        selectedNode.Nodes.Add(trvNode);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                  string errorMsg = ex.Message;
                if (ex.InnerException != null)
                    errorMsg += ex.InnerException.Message;
                  MessageBox.Show(errorMsg,
                         "FileTransferProfile Application",
                          MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion
    }
}